$(document).ready(function() {

	$("#paymentSDate").datepicker({
		monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
		dayNamesMin:["일","월","화","수","목","금","토"],
		changeMonth: true,    //달력 셀렉트 박스 유무
		changeYear: true,    //년 셀렉트 박스 유무
		buttonImageOnly : true,
		showOn: 'both',	//버튼노출
		buttonImage : "images/butt_calender.gif",
		dateFormat: "yymmdd", //날짜 출력 형식
	});
	
	$("#paymentEDate").datepicker({
		monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
		dayNamesMin:["일","월","화","수","목","금","토"],
		changeMonth: true,    //달력 셀렉트 박스 유무
		changeYear: true,    //년 셀렉트 박스 유무
		buttonImageOnly : true,
		showOn: 'both',	//버튼노출
		buttonImage : "images/butt_calender.gif",
		dateFormat: "yymmdd", //날짜 출력 형식
	});
	
	var dataSet = new Array();
	var newId = 0;
	var lastSel = -1;
	
	$("#grid").jqGrid({
		caption : "직원조회",
	    height : "100%",
	    rowNum : 10,
	    rowList : [10,20,30],
	    colNames : ["부서명","사원번호","성명","월기준급여"],
		colModel : [
		            {name: "CODE_NAME", width : 100 },
		            {name: "EMPLOYEE_ID", width : 100 },
		            {name: "NAME", width : 100 },
		            {name: "SALARY", width : 100 }
		           ]
		}).navGrid("#pager",{
			search : true,
			edit : true,
			add : true,
			del : true
		});
	
	$("#grid2").jqGrid({
		pager: "#pager2",
		caption : "보너스 대상자",
	    height : "200",
	    rowNum : 10,
	    rowList : [10,20,30],
	    colNames : ["사원번호","성명","지급일자","보너스종류","보너스금액","CRUD"
	                ,"PK","ID"],
		colModel : [
		            {name: "EMPLOYEE_ID", width : 100 },
		            {name: "NAME", width : 100 },
		            {name: "PAYMENT_DATE", width : 100, editable : true },
		            {name: "BONUS_NAME", width : 100, editable : true, edittype:"select",editoptions:{value:"B1:기본;B2:업적;B3:특별"}  },
		            {name: "BONUS_SUM", width : 100, editable : true },
		            {name: "CRUD", hidden: true},
		            {name: "PK" , hidden: true},
		            {name: "ID", hidden: true}
		           ],
	   editurl: "clientArray",
       onSelectRow : function(id){   
    	   				console.log("============== start: onSelectRow id="+id);
    	   				
    	   				if( id && id !== lastSel){
    	   					jQuery('#grid2').jqGrid('saveRow',lastSel,false);
    	   					
    	   					var lastSelData = $("#grid2").jqGrid("getRowData",lastSel);
    	   					    	   					
    	   					for (var i = 0; i < dataSet.length; i++) {
    	   						if(lastSelData.ID == dataSet[i].ID ){
    	   							if( !compareCurToLastData(dataSet[i], lastSelData) ){
    	   								setUpdate(dataSet[i]);
    	   								console.log("CRUD : "+dataSet[i].CRUD);
    	   							}
    	   							
    	   						}
								
							}
    	   					
    	   					lastSel = id;
    	   				}
    	   				
    	   				$("#grid2").jqGrid("editRow",id,true,pickdates);
    	   				
    	   				console.log("============== end: onSelectRow id="+id);
    	       		}
			}).navGrid("#pager2",{
			search : true,
			edit : true,
			add : true,
			del : true
			});
	
	$.ajax({
		url : "getBNS.do",
		dataType : "json",
		type : "get",
		success : function(data) {
			
			var rows = data.rows;
			
			for (var i = 0, len = rows.length; i < len; i++) {
				$("#grid").jqGrid("addRowData",i,rows[i]);
			}
		}
	});
	
	$.ajax({
		url : "getBNS2.do",
		dataType : "json",
		type : "get",
		success : function(data) {
			
			var rows = data.rows;
			
			for (var i = 0, len = rows.length; i < len; i++) {
				rows[i].CRUD = "R";
				rows[i].PK = [rows[i].EMPLOYEE_ID, rows[i].PAYMENT_DATE, rows[i].BONUS_CODE];
				rows[i].ID = newId;
				dataSet.push(rows[i]);
				
				$("#grid2").jqGrid("addRowData",newId++,rows[i]);
			}
		}
	});
	
	$("#search").click(function() {
		var deptCode=$("#deptCode").val();
		var bonusCode=$("#bonusCode").val();
		var paymentSDate=$("#paymentSDate").val();
		var paymentEDate=$("#paymentEDate").val();
		
		$.ajax({
			url : "getBNS.do?deptCode="+deptCode,
			dataType : "json",
			type : "get",
			success : function(data) {
				//console.log(data);
				
				var rows = data.rows;
				
				$("#grid").jqGrid("clearGridData");
				
				for (var i = 0, len = rows.length; i < len; i++) {
					$("#grid").jqGrid("addRowData",i,rows[i]);
					
				}
			}
		});
		
		$.ajax({
			url : "getBNS2.do?deptCode="+deptCode+"&bonusCode="+bonusCode+"&paymentSDate="
			+paymentSDate+"&paymentEDate="+paymentEDate,
			dataType : "json",
			type : "get",
			success : function(data) {
				
				var rows = data.rows;
				newId = 0;
				dataSet = new Array();
				
				$("#grid2").jqGrid("clearGridData");
				
				for (var i = 0, len = rows.length; i < len; i++) {
					rows[i].CRUD = "R";
					rows[i].PK = [rows[i].EMPLOYEE_ID, rows[i].PAYMENT_DATE, rows[i].BONUS_CODE];
					rows[i].ID = newId;
					
					dataSet.push(rows[i]);
					
					$("#grid2").jqGrid("addRowData",newId++,rows[i]);
				}
			}
		});	
		
		
	});
	
	$("#add").click(function() {
		
		console.log("============== start: add");
		
		var selRow = $("#grid").jqGrid("getGridParam","selrow");
		var selData = $("#grid").jqGrid("getRowData",selRow);
		var now = new Date();
		var selectBox = document.getElementById("bonusCode");
		
		selData["BONUS_NAME"] = selectBox.options[selectBox.selectedIndex].text;
		selData["BONUS_CODE"] = $("#bonusCode").val();
		selData["BONUS_SUM"] = (selData["SALARY"]*0.1).toFixed(2); 
		selData["PAYMENT_DATE"] =""+now.getFullYear()
				+((now.getMonth()+1) < 10 ? "0"+(now.getMonth()+1) : now.getMonth()+1 ) 
				+(now.getDate() < 10 ? "0"+now.getDate() : now.getDate() );
		selData["CRUD"] = "C";
		selData["ID"] = newId;
		
		dataSet.push(selData);
		
		$("#grid2").jqGrid("addRowData",newId++,selData);
		console.log("CRUD: "+selData.CRUD);
		console.log("============== end: add");
	});
	
	$("#delete").click(function() {
		console.log("============== start: delete");
		
		var selRow = $("#grid2").jqGrid("getGridParam","selrow");
		jQuery('#grid2').jqGrid('saveRow',selRow,false);
		var selData = $("#grid2").jqGrid("getRowData",selRow);
		
		for (var i = 0; i < dataSet.length; i++) {
			if( selData.ID == dataSet[i].ID ){
				setDelete(dataSet[i]);
				console.log("CRUD "+dataSet[i].CRUD);
			}
		}
				
		$("#grid2").jqGrid("delRowData",selRow);
		
		
		
		console.log("============== end: delete");
	});

	$("#save").click(function() {
		
		console.log("============== start: save");
		
		jQuery('#grid2').jqGrid('saveRow',lastSel,false);
		
		var curSelRow = $("#grid2").jqGrid("getGridParam","selrow");
		$("#grid2").jqGrid("saveRow",curSelRow);
		var curSelData = $("#grid2").jqGrid("getRowData",curSelRow);
		
		for (var i = 0; i < dataSet.length; i++) {
				if( dataSet[i].ID == curSelData.ID){
					if( !compareCurToLastData(curSelData, dataSet[i]) ){
						 setUpdate(dataSet[i]);
						 
					}
				}
		}
		
		saveData();
		
		$.ajax({
			url : "doSaveBNS.do",
			dataType : "json",
			type : "post",
			contentType : "application/json",
			data : JSON.stringify(dataSet),
			success : function(data) {
				if(data != ""){
					alert(data);
					
				}
				return true;
			}
		});
		
		clearDataSet(dataSet);
		
		console.log("============== end: save");
	});
	
	function saveData() {
		
		console.log("============== start: saveData");
		
		var dataArray = jQuery('#grid2').jqGrid('getRowData');
		
		console.log("dataArray : "+dataArray);
			
		for (var i = 0; i < dataArray.length; i++) {
			var data = dataArray[i];
			
			for (var j = 0; j < dataSet.length; j++) {
				if (data.ID == dataSet[j].ID ){
					dataSet[j].PAYMENT_DATE = data.PAYMENT_DATE;
					dataSet[j].BONUS_CODE = data.BONUS_CODE;
					dataSet[j].BONUS_SUM = data.BONUS_SUM;
					dataSet[j].BONUS_CODE = bonusNameToCode(data.BONUS_NAME);
					
				}
			}
		}
		
		
		
		console.log("dataSet: "+dataSet);
		console.log("============== end: saveData");
	}
	
	function bonusNameToCode(name) {
		var code;
		
		switch(name){
			case "기본" : 
				code = "B1";
				break;
			case "업적" : 
				code = "B2";
				break;
			case "특별" : 
				code = "B3";
				break;
			default:
				break;
		}
		
		return code;
	}
	
	function bonusCodeToName(code) {
		var name;
		
		switch(code){
		case "B1" : 
			name = "기본";
			break;
		case "B2" : 
			name = "업적";
			break;
		case "B3" : 
			name = "특별";
			break;
		default:
			break;
		}
		
		return name;
	}
	
	function compareCurToLastData(curSelData,lastSelData) {
		if(curSelData.PAYMENT_DATE != lastSelData.PAYMENT_DATE 
					|| curSelData.BONUS_NAME != lastSelData.BONUS_NAME
					|| curSelData.BONUS_SUM != lastSelData.BONUS_SUM){
				return false;
			}
		
		return true;
	}
	
	function setUpdate(data) {
		if( data.CRUD == "R" ){
			data.CRUD = "U";
		}
	}
	function setDelete(data) {
		if( data.CRUD == "R" || data.CRUD == "U"){
			data.CRUD = "D";
		}else if( data.CRUD == "C"){
			dataSet = dataSet.filter(function(x) {
				 return x.ID != data.ID;
				
			});
		}
	}
	
	function clearDataSet(dataSet) {
		newId = 0;
		
		for (var i = 0; i < dataSet.length; i++) {
			dataSet[i].CRUD = "R";
			dataSet[i].ID = newId++;
		}
		
		
	}
	function pickdates(id){
		console.log("start: pickdates");
		
		jQuery("#"+id+"_PAYMENT_DATE","#grid2").datepicker({dateFormat:"yymmdd"});
		
		console.log("end: pickdates");
	}
});